package com.bigboss.knowstar.service.impl;

import com.bigboss.knowstar.exception.FileUploadException;
import com.bigboss.knowstar.service.IUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class LocalUploadServiceImpl implements IUploadService {

    @Value("${local-upload-path}")
    private String realPath;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy\\MM\\dd\\");

    @Override
    public String uploadFile(MultipartFile file, HttpServletRequest req, String type) {
        if (file == null || file.isEmpty()) {
            throw new FileUploadException("文件为空，无法上传");
        }
//        String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldFileName = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString() + oldFileName.substring(oldFileName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newFileName));
//            String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + format + newFileName;
//            System.out.println(realPath);
//            System.out.println(format);
//            System.out.println(newFileName);
            return realPath + format + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "文件上传失败";
    }

    @Override
    public List<String> multiUploadFiles(MultipartFile[] files, HttpServletRequest req, String type) {
        List<String> filePaths = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file == null || file.isEmpty()) {
                throw new FileUploadException("文件为空，无法上传");
            }
            filePaths.add(uploadFile(file, req, type));
        }
        return filePaths;
    }


}
